<?php

App::import('Vendor', 'allegro/AllegroWebAPISoapClient');
class AdvertisementsController extends AppController {

	public $uses = array("Advertisement");
	public $components = array('Paginator');
	public $helpers = array('Paginator');
	
	public function index() {
		$paginate = array();
		$paginate['limit'] = 5;
		$paginate['order'] = array(
				'Advertisement.title' => 'asc'
		);
		if (!$this->isLoggedUserAdmin()) {
			$paginate['conditions'] = array('author_id' => $this->getLoggedUserId());
		}
		
		$this->Paginator->settings = $paginate;
		$adverts = $this->Paginator->paginate('Advertisement');
		$this->set('advertisements', $adverts);
		$this->set('isLoggedUserAdmin', $this->isLoggedUserAdmin());
	}
	
	private function escapeJavaScriptText($string) 
	{ 
	    return str_replace("<br/>", '<br/>', str_replace('"', '\"', addcslashes(str_replace("\r", '', (string)$string), "\0..\37'\\"))); 
	} 
		
	public function add() {
		if ($this->request->is('post')) {
			$this->Advertisement->create();
			$data = $this->request->data;
			$image = $this->request->form['image'];
						
			
            $data['status_id'] = Advertisement::ROBOCZE;
            $data['author_id'] = $this->getLoggedUserId();
            
            $data['content'] = $this->escapeJavaScriptText($data['content']);
            
            // data replace 
            
            $this->saveAdvertisement($data, $image);
        }
    }
    
	public function edit($advertisementId) {
		$this->Advertisement->id = $advertisementId;
        if ($this->request->is('get')) {
        	if (!$this->Advertisement->exists()) {
                throw new NotFoundException(__('Brak takiego ogłoszenia'), 'msg');
            }
            $this->set('advertisement', $this->Advertisement->findById($advertisementId));
            
        } else {
			$data = $this->request->data;
            $this->saveAdvertisement($data);
        }
    }
    
	public function delete($advertisementId) {
		if (!$this->request->is('GET')) {
			throw new MethodNotAllowedException();
		}
		
		$this->Advertisement->id = $advertisementId;
		if (!$this->Advertisement->exists()) {
			throw new NotFoundException(__('Brak takiego ogłoszenia'), 'msg');
		}
		
		if ($this->Advertisement->delete()) {
			$this->Session->setFlash(__('Ogłoszenie zostało usunięte.'), 'msg');
		}
		return $this->redirect(array('action' => 'index'));
	}
	
	public function unpublish($advertisementId) {
		if (!$this->request->is('GET')) {
			throw new MethodNotAllowedException();
		}
		
		$this->Advertisement->id = $advertisementId;
		if (!$this->Advertisement->exists()) {
			throw new NotFoundException(__('Brak takiego ogłoszenia'), 'msg');
		}
		
		$this->Advertisement->set("status_id", Advertisement::ROBOCZE);
		if ($this->Advertisement->save()) {
			$this->Session->setFlash(__('Status ogłoszenia został zmnieniony na robocze.'), 'msg');
		}
		return $this->redirect(array('action' => 'index'));
	}
	
	public function publish($advertisementId) {
		if (!$this->request->is('GET')) {
			throw new MethodNotAllowedException();
		}
		
		$this->Advertisement->id = $advertisementId;
		if (!$this->Advertisement->exists()) {
			throw new NotFoundException(__('Brak takiego ogłoszenia'), 'msg');
		}
		
		$this->Advertisement->set("status_id", Advertisement::OPUBLIKOWANE);
		if ($this->Advertisement->save()) {
			$this->Session->setFlash(__('Ogłoszenie zostało opublikowane.'), 'msg');
		}
		return $this->redirect(array('action' => 'index'));
	}

	public function testAllegro() {
		try {
			$client = new SoapClient('http://webapi.allegro.pl/uploader.php?wsdl');
			$version = $client->doQuerySysStatus(AllegroWebAPISoapClient::QUERY_ALLEGROWEBAPI, AllegroWebAPISoapClient::ALLEGRO_COUNTRY_TEST, AllegroWebAPISoapClient::ALLEGRO_KEY);
			echo 'Zwrocono wersję:<br/>';
			echo 'Wersja AllegroWebAPI: ' + $version['info'].'<br/>';
			echo 'Klucz wersji: ' + $version['ver-key'].'<br/>';
			echo 'Trwa logowanie...<br/>';
			
			try {
				$session = $client->doLoginEnc(AllegroWebAPISoapClient::ALLEGRO_LOGIN, base64_encode( hash('sha256', AllegroWebAPISoapClient::ALLEGRO_PASSWORD, true) ),
					 AllegroWebAPISoapClient::ALLEGRO_COUNTRY_TEST, AllegroWebAPISoapClient::ALLEGRO_KEY, $version['ver-key']);
			} catch(SoapFault $error) {
				echo $e;
			}
			echo 'Zalogowano<br/>';
			
			$sessionKey = $session['session-handle-part'];
			$allegroServerTime = $session['server-time'];

			
		} catch (Exception $e) {
			echo $e;
		}
	}
	
    private function saveAdvertisement($data, $image) {
    	$data['image_name'] = $image['name'];;
    	$data['image_path'] = 'uploads/'.$image['name'];
    	$data['image_size'] = $image['size'];

        if ($this->Advertisement->save($data)) {
            move_uploaded_file($image['tmp_name'], WWW_ROOT.'uploads/'.$image['name']);
            $this->Session->setFlash(__('Ogłoszenie zostało zapisane.'), 'msg');
                 
        } else {
            foreach ($this->Advertisement->validationErrors as $key => $value) {
                $this->Session->setFlash(__($value[0]), 'warning');
            }
        }
        return $this->redirect(array('action' => 'index'));
    }
}